// 文件路径：src/main/java/com/example/demo/controller/ChatController.java
package com.example.demo.controller;

import com.example.demo.entity.ChatMessage;
import com.example.demo.mapper.ChatMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Controller
public class ChatController {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    // 在线用户会话映射（模拟，实际可用 Redis 或 SecurityContext 替代）
    private static final Map<Long, String> userSessions = new ConcurrentHashMap<>();

    // 设置当前用户 ID（供前端调用切换身份）
    @PostMapping("/chat/login")
    @ResponseBody
    public String login(@RequestBody Map<String, Long> payload) {
        Long userId = payload.get("userId");
        userSessions.put(userId, "online");
        log.info("用户登录: " + userId);
        return "OK";
    }

    // 处理聊天消息：A 发送给 B 或 C
    @MessageMapping("/chat/{receiverId}")
    public void handleMessage(@DestinationVariable Long receiverId, ChatMessage message) {
        message.setSenderId(message.getSenderId());
        message.setReceiverId(receiverId);
        message.setSendTime(new java.util.Date());
        message.setIsRead(false);

        chatMessageMapper.insertMessage(message);

        // ✅ 正确用法：Spring 会自动将消息发送给指定用户的唯一会话
        messagingTemplate.convertAndSendToUser(
                receiverId.toString(),   // 用户ID作为目标
                "/queue/messages",       // 客户端订阅的路径
                message                  // 消息体
        );

        log.info("消息已发送: {} -> {}", message.getSenderId(), receiverId);
    }

    // 标记消息为已读，并通知发送者（已读回执）
    @MessageMapping("/mark-as-read")
    @SendToUser("/queue/read-receipt")
    public ChatMessage markAsRead(ChatMessage message) {
        chatMessageMapper.markAsRead(message.getId());
        log.info("消息已读更新：" + message.getId());

        // 回执中包含原消息信息和接收者ID，便于A识别是哪个对话的回执
        return message;
    }

    // 获取两个用户之间的聊天历史
    @GetMapping("/chat/history")
    @ResponseBody
    public List<ChatMessage> getChatHistory(
            @RequestParam Long user1,
            @RequestParam Long user2) {
        return chatMessageMapper.selectChatHistory(user1, user2);
    }

    // 获取某用户的未读消息数
    @GetMapping("/chat/unread-count")
    @ResponseBody
    public Map<String, Integer> getUnreadCount(@RequestParam Long userId) {
        int count = chatMessageMapper.getUnreadCount(userId);
        return Map.of("count", count);
    }
}
